这是一款文件加密工具,采用字节交换和位操作两种加密方式,简单方便。 byte[] result=null;
if (rbByte.Checked)//按字节交换方式加密
{
int length = 0;
//如果填写的是整数
if (int.TryParse(txtByteLength.Text, out length))
{
FileByteSecurity fbs = new FileByteSecurity(txtFileName.Text);
result= fbs.ExchangeByte(length);
}
}
else//按位操作方式加密
{
BitOperation bitOperation = new BitOperation(txtFileName.Text);
result = bitOperation.Operation();
}
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.CheckFileExists = false;
saveDialog.CheckPathExists = true;
saveDialog.DefaultExt = "Text files (*.txt)|*.txt";
saveDialog.Filter = "Text files (*.txt)|*.txt|doc files (*.doc)|*.doc|jpg files (*.jpg)|*.jpg|All files (*.*)|*.*";
if (saveDialog.ShowDialog(this) == DialogResult.OK&&result!=null)
{
FileInfo fileInfo = new FileInfo(saveDialog.FileName);
FileStream stream=fileInfo.Create();
//StreamWriter writer = new StreamWriter(stream);
stream.Write(result, 0, result.Length);
stream.Close();
}
// 说明:对文件字节顺序进行操作的类 public sealed class FileByteSecurity
{
private int fileLength;
private string fileName;
private FileInfo fileInfo;
/// <summary>
/// 文件名
/// </summary>
public string FileName
{
get { return fileName; }
set
{
if (fileInfo != null)
{
fileInfo = null;//将当前文件置空,释放资源
}
//如果更改了文件名,则重新创建FileInfo实例
//fileInfo = new FileInfo(fileName);
SetFileName(value);
}
}
/// <summary>
/// 获取文件大小
/// </summary>
public long FileLength
{
get
{
return fileLength;
}
}
public FileByteSecurity()
{
}
public FileByteSecurity(string fileName)
{
SetFileName(fileName);
}
private void SetFileName(string fileName)
{
this.fileName = fileName;
fileInfo = new FileInfo(fileName);
long length = fileInfo.Length;
if (length <= Int32.MaxValue)
{
fileLength = (int)length;
}
}
/// <summary>
/// 将文件的字节内容前后调换
/// </summary>
/// <param name="byteLength">要调换的字节数</param>
/// <returns>返回调换后的字节内容</returns>
public byte[] ExchangeByte(int byteLength)
{
if (fileInfo.Length < 2 * byteLength)
{
throw new ArgumentOutOfRangeException("byteLength", byteLength, "超过了实际文件大小");
}
else
{
FileStream stream = fileInfo.OpenRead();
byte[] total = new byte[fileLength];//存储文件内容的字节数组
stream.Read(total, 0,fileLength);
stream.Close();
byte tempByte;//用于交换文件字节的数据
//下面的循环实现文件的首字节与文件的尾字节对换
//文件的第二字节与文件倒数第二字节对换
//假设文件的字节长度为length,那么对换字节的索引n,m满足:n m=length-1
//也就是n=length-m-1
for (int i = 0; i < byteLength; i )
{
tempByte = total[i];
total[i] = total[fileLength - 1 - i];
total[fileLength - 1 - i] = tempByte;
}
return total;//返回调整次序后的文件字节内容
}
}
}
评论